<?php

namespace App\Admin\Controllers;

use App\Models\Store;
use App\Models\User;
use App\Models\AdminUser;
use App\Models\StaffAuth;
use App\Models\StoreCashierSwitchCodeGroup;
use App\Models\StoreCashierSwitchCodeGroupProperties;
use App\Models\StoreCashierSwitchCodeGroupRelation;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class StoreGoodsController extends VuePageController
{
    /**
     * 门店商品列表
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        // 添加百度地图API脚本
        // Admin::script('https://api.map.baidu.com/api?v=2.0&ak=b6WWqwPeGhsb9Wg7Sdvyf8vUOIGf3579');
        
        $content = $this->vue($content);
        return $content
            ->title('门店商品管理')
            ->description('门店商品清单')
            ->body(view('admin.store_goods.list'));
    }


    /**
     * 商品列表接口（查询所有门店的商品）
     * 供后台商品清单页面使用
     */
    public function goodsList(Request $request)
    {
        $page = max(1, (int) $request->input('page', 1));
        $limit = max(1, min(100, (int) $request->input('limit', 10)));
        
        // 获取请求参数
        $title = $request->input('title', ''); // 商品名称
        $storeName = $request->input('store_name', ''); // 门店名称
        $storeId = $request->input('store_id', ''); // 门店ID（可选）
        $categoryId = $request->input('categoryId', ''); // 分类ID
        $categoryId1 = $request->input('categoryId1', ''); // 一级分类ID
        $categoryId2 = $request->input('categoryId2', ''); // 二级分类ID
        $status = $request->input('status', ''); // 商品状态（0=下架，1=上架）
        $hasOption = $request->input('hasOption', ''); // 是否有规格
        $brandId = $request->input('brandId', ''); // 品牌ID
        $isSoldOut = $request->input('isSoldOut', ''); // 是否售罄（库存为0）
        
        // 构建查询条件
        $query = DB::table('ims_hhm_goods as g')
            ->leftJoin('ims_hhm_category as c1', 'g.category_id_1', '=', 'c1.id')
            ->leftJoin('ims_hhm_category as c2', 'g.category_id_2', '=', 'c2.id')
            ->leftJoin('ims_yz_store as s', 'g.store_id', '=', 's.id')
            ->select([
                'g.id',
                'g.title',
                'g.alias',
                'g.thumb',
                'g.price',
                'g.market_price',
                'g.cost_price',
                'g.stock',
                'g.status',
                'g.has_option',
                'g.option_count',
                'g.real_sales',
                'g.virtual_sales',
                'g.show_sales',
                'g.created_at',
                'g.updated_at',
                'g.display_order',
                'g.store_id',
                'c1.name as category_1_name',
                'c2.name as category_2_name',
                's.store_name',
                'g.is_recommand'
            ]);
        
        // 默认只查询未删除的商品
        $query->where('g.is_deleted', 0);
        
        // 门店筛选（可选，不传则查询所有门店）
        if (!empty($storeId)) {
            $query->where('g.store_id', $storeId);
        }
        
        // 门店名称筛选
        if (!empty($storeName)) {
            $query->where('s.store_name', 'like', '%' . $storeName . '%');
        }
        
        // 商品名称筛选
        if (!empty($title)) {
            $query->where('g.title', 'like', '%' . $title . '%');
        }
        
        // 分类筛选：优先使用二级分类，如果没有二级分类则使用一级分类
        if (!empty($categoryId2)) {
            $query->where('g.category_id_2', $categoryId2);
        } elseif (!empty($categoryId1)) {
            $query->where('g.category_id_1', $categoryId1);
        } elseif (!empty($categoryId)) {
            // 兼容旧接口，如果只传了categoryId，则匹配一级或二级分类
            $query->where(function($q) use ($categoryId) {
                $q->where('g.category_id_1', $categoryId)
                  ->orWhere('g.category_id_2', $categoryId);
            });
        }
        
        // 商品状态筛选
        if ($status !== '') {
            $query->where('g.status', $status);
        }
        
        // 是否有规格筛选
        if ($hasOption !== '') {
            $query->where('g.has_option', $hasOption);
        }
        
        // 品牌筛选
        if (!empty($brandId)) {
            $query->where('g.brand_id', $brandId);
        }
        
        // 售罄筛选（库存为0）
        if ($isSoldOut == 1) {
            $query->where('g.stock', 0);
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取上架中和下架中的数量统计（不限制门店）
        $statusStatsQuery = DB::table('ims_hhm_goods as g')
            ->where('g.is_deleted', 0);
        
        // 如果指定了门店筛选，统计也加上
        if (!empty($storeId)) {
            $statusStatsQuery->where('g.store_id', $storeId);
        }
        
        // 如果指定了门店名称筛选，统计也加上
        if (!empty($storeName)) {
            $statusStatsQuery->leftJoin('ims_yz_store as s', 'g.store_id', '=', 's.id')
                ->where('s.store_name', 'like', '%' . $storeName . '%');
        }
        
        // 如果指定了其他筛选条件，统计也需要加上（保持与主查询一致）
        if (!empty($title)) {
            $statusStatsQuery->where('g.title', 'like', '%' . $title . '%');
        }
        
        if (!empty($categoryId2)) {
            $statusStatsQuery->where('g.category_id_2', $categoryId2);
        } elseif (!empty($categoryId1)) {
            $statusStatsQuery->where('g.category_id_1', $categoryId1);
        } elseif (!empty($categoryId)) {
            $statusStatsQuery->where(function($q) use ($categoryId) {
                $q->where('g.category_id_1', $categoryId)
                  ->orWhere('g.category_id_2', $categoryId);
            });
        }
        
        if ($status !== '') {
            $statusStatsQuery->where('g.status', $status);
        }
        
        if ($hasOption !== '') {
            $statusStatsQuery->where('g.has_option', $hasOption);
        }
        
        if (!empty($brandId)) {
            $statusStatsQuery->where('g.brand_id', $brandId);
        }
        
        if ($isSoldOut == 1) {
            $statusStatsQuery->where('g.stock', 0);
        }
        
        $statusStats = $statusStatsQuery->select([
            DB::raw('SUM(CASE WHEN g.status = 1 THEN 1 ELSE 0 END) as online_count'),
            DB::raw('SUM(CASE WHEN g.status = 0 THEN 1 ELSE 0 END) as offline_count')
        ])->first();
        
        // 分页查询
        $goods = $query->orderBy('g.created_at', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
        
        // 处理商品状态显示
        $statusMap = [
            0 => '下架',
            1 => '上架'
        ];
        
        // 处理数据
        foreach ($goods as $item) {
            $item->status_text = $statusMap[$item->status] ?? '未知状态';
            $item->created_at = date('Y-m-d H:i:s', $item->created_at);
            $item->updated_at = date('Y-m-d H:i:s', $item->updated_at);
            $item->total_sales = ($item->real_sales ?? 0) + ($item->virtual_sales ?? 0);
        }
        
        $data = [
            'list' => $goods,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit),
            'stats' => [
                'online_count' => $statusStats->online_count ?? 0,
                'offline_count' => $statusStats->offline_count ?? 0
            ]
        ];
        
        return response()->json([
            'result' => 1,
            'msg' => '获取商品列表成功',
            'data' => $data
        ]);
    }

    /**
     * 商品详情页（编辑）
     */
    public function detailPage(Content $content)
    {
        $content = $this->vue($content);
        return $content
            ->title('商品管理')
            ->description('商品详情')
            ->body(view('admin.store_goods.detail'));
    }

    /**
     * 获取商品详情（后台用，不限制门店）
     */
    public function getDetail(Request $request)
    {
        $goodsId = (int) $request->input('goods_id', 0);
        if ($goodsId <= 0) {
            return response()->json([
                'result' => 0,
                'msg' => '商品ID不能为空'
            ]);
        }

        $goods = DB::table('ims_hhm_goods as g')
            ->leftJoin('ims_hhm_category as c1', 'g.category_id_1', '=', 'c1.id')
            ->leftJoin('ims_hhm_category as c2', 'g.category_id_2', '=', 'c2.id')
            ->leftJoin('ims_yz_store as s', 'g.store_id', '=', 's.id')
            ->where('g.id', $goodsId)
            ->where('g.is_deleted', 0)
            ->select([
                'g.*',
                'c1.name as category_1_name',
                'c2.name as category_2_name',
                's.store_name'
            ])->first();

        if (!$goods) {
            return response()->json([
                'result' => 0,
                'msg' => '商品不存在或已删除'
            ]);
        }

        // 规格
        $specs = [];
        $options = [];
        if (!empty($goods->has_option)) {
            $specs = DB::table('ims_hhm_goods_spec')
                ->where('goods_id', $goodsId)
                ->orderBy('display_order')
                ->get();
            foreach ($specs as $spec) {
                $spec->items = DB::table('ims_hhm_goods_spec_item')
                    ->where('spec_id', $spec->id)
                    ->orderBy('display_order')
                    ->get();
            }
            $options = DB::table('ims_hhm_goods_option')
                ->where('goods_id', $goodsId)
                ->orderBy('display_order')
                ->get();
        }

        return response()->json([
            'result' => 1,
            'msg' => '获取商品详情成功',
            'data' => [
                'goods' => $goods,
                'specs' => $specs,
                'options' => $options,
            ],
        ]);
    }

    /**
     * 批量更新商品（后台用，可跨门店操作）
     */
    public function batchUpdate(Request $request)
    {
        $ids = $request->input('ids', []);
        $status = $request->input('status', null);
        $categoryId1 = $request->input('category_id_1', null);
        $categoryId2 = $request->input('category_id_2', null);
        
        if (empty($ids) || !is_array($ids)) {
            return response()->json([
                'result' => 0,
                'msg' => '请选择要更新的商品'
            ]);
        }
        
        try {
            DB::beginTransaction();
            
            $updateData = [];
            if ($status !== null) {
                $updateData['status'] = $status;
            }
            if ($categoryId1 !== null) {
                $updateData['category_id_1'] = $categoryId1;
            }
            if ($categoryId2 !== null) {
                $updateData['category_id_2'] = $categoryId2;
            }
            
            if (empty($updateData)) {
                return response()->json([
                    'result' => 0,
                    'msg' => '没有要更新的数据'
                ]);
            }
            
            $updateData['updated_at'] = time();
            
            // 批量更新商品（不限制门店）
            $affectedRows = DB::table('ims_hhm_goods')
                ->whereIn('id', $ids)
                ->where('is_deleted', 0)
                ->update($updateData);
            
            // 如果更新了分类，同步更新分类关联表
            if ($categoryId1 !== null || $categoryId2 !== null) {
                $categoryIds = [];
                if ($categoryId1) {
                    $categoryIds[] = $categoryId1;
                }
                if ($categoryId2) {
                    $categoryIds[] = $categoryId2;
                }
                
                foreach ($ids as $goodsId) {
                    // 删除原有关联
                    DB::table('ims_hhm_goods_category')->where('goods_id', $goodsId)->delete();
                    
                    if (!empty($categoryIds)) {
                        $categoryIdsStr = implode(',', $categoryIds);
                        $childCategoryId = end($categoryIds);
                        
                        DB::table('ims_hhm_goods_category')->insert([
                            'goods_id' => $goodsId,
                            'category_id' => $childCategoryId,
                            'category_ids' => $categoryIdsStr,
                            'created_at' => time(),
                            'updated_at' => time(),
                        ]);
                    }
                }
            }
            
            DB::commit();
            
            return response()->json([
                'result' => 1,
                'msg' => '批量更新成功',
                'data' => ['affected_rows' => $affectedRows]
            ]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'result' => 0,
                'msg' => '批量更新失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新单个商品（后台用，可跨门店操作）
     * 注意：方法名改为 updateGoods 避免与基类 update($id) 方法冲突
     */
    public function updateGoods(Request $request)
    {
        $goodsId = $request->input('goods_id', 0);
        // 接收可更新字段
        $payload = $request->all();
        
        if (empty($goodsId)) {
            return response()->json([
                'result' => 0,
                'msg' => '商品ID不能为空'
            ]);
        }
        
        try {
            // 允许更新的字段（与门店端保持一致）
            $allowedFields = [
                'title', 'alias', 'sku', 'thumb', 'thumb_url', 'video_url',
                'category_id_1', 'category_id_2',
                'market_price', 'price', 'cost_price', 'stock',
                'reduce_stock_method', 'has_option', 'weight', 'volume',
                'goods_sn', 'product_sn', 'description', 'content',
                'min_buy', 'max_buy', 'is_limit', 'need_address', 'no_refund',
                'status', 'display_order', 'is_recommand'
            ];
            $updateData = [];
            foreach ($allowedFields as $field) {
                if (array_key_exists($field, $payload)) {
                    // thumb_url 允许数组，入库转为json
                    if ($field === 'thumb_url' && is_array($payload[$field])) {
                        $updateData[$field] = json_encode($payload[$field]);
                    } else {
                        $updateData[$field] = $payload[$field];
                    }
                }
            }
            
            if (empty($updateData)) {
                return response()->json([
                    'result' => 0,
                    'msg' => '没有要更新的数据'
                ]);
            }
            
            $updateData['updated_at'] = time();
            
            $affectedRows = DB::table('ims_hhm_goods')
                ->where('id', $goodsId)
                ->where('is_deleted', 0)
                ->update($updateData);
            
            if ($affectedRows > 0) {
                return response()->json([
                    'result' => 1,
                    'msg' => '更新成功'
                ]);
            } else {
                return response()->json([
                    'result' => 0,
                    'msg' => '商品不存在或已被删除'
                ]);
            }
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg' => '更新失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新商品规格
     */
    public function updateSpecs(Request $request)
    {
        $goodsId = $request->input('goods_id');
        $hasOption = $request->input('has_option', 0);
        $specs = $request->input('specs', []);
        $options = $request->input('options', []);

        if (!$goodsId) {
            return response()->json([
                'result' => 0,
                'msg' => '商品ID不能为空'
            ]);
        }

        try {
            DB::beginTransaction();

            // 更新商品的 has_option 字段
            DB::table('ims_hhm_goods')
                ->where('id', $goodsId)
                ->update([
                    'has_option' => $hasOption,
                    'updated_at' => time()
                ]);

            // 删除旧的规格数据
            $oldSpecIds = DB::table('ims_hhm_goods_spec')
                ->where('goods_id', $goodsId)
                ->pluck('id');
            
            if ($oldSpecIds->isNotEmpty()) {
                DB::table('ims_hhm_goods_spec_item')->whereIn('spec_id', $oldSpecIds)->delete();
            }
            DB::table('ims_hhm_goods_spec')->where('goods_id', $goodsId)->delete();
            DB::table('ims_hhm_goods_option')->where('goods_id', $goodsId)->delete();

            // 如果启用了规格，保存新的规格数据
            if ($hasOption && !empty($specs)) {
                $specIdMap = []; // 用于映射旧的 spec title 到新的 spec_id

                // 保存规格
                foreach ($specs as $index => $spec) {
                    $specId = DB::table('ims_hhm_goods_spec')->insertGetId([
                        'goods_id' => $goodsId,
                        'title' => $spec['title'],
                        'display_order' => $index,
                        'created_at' => time(),
                        'updated_at' => time()
                    ]);

                    $specIdMap[$spec['title']] = $specId;

                    // 保存规格项
                    if (!empty($spec['items'])) {
                        foreach ($spec['items'] as $itemIndex => $item) {
                            DB::table('ims_hhm_goods_spec_item')->insert([
                                'spec_id' => $specId,
                                'title' => $item['title'],
                                'display_order' => $itemIndex,
                                'created_at' => time(),
                                'updated_at' => time()
                            ]);
                        }
                    }
                }

                // 保存规格选项（SKU）
                if (!empty($options)) {
                    foreach ($options as $index => $option) {
                        // 构建规格标题字符串（用于显示）
                        $specTitles = [];
                        foreach ($specs as $spec) {
                            if (isset($option[$spec['title']])) {
                                $specTitles[] = $option[$spec['title']];
                            }
                        }

                        DB::table('ims_hhm_goods_option')->insert([
                            'goods_id' => $goodsId,
                            'spec_titles' => implode(',', $specTitles),
                            'specs' => json_encode($option['specs'] ?? []),
                            'stock' => $option['stock'] ?? 0,
                            'market_price' => $option['market_price'] ?? 0,
                            'product_price' => $option['product_price'] ?? 0,
                            'cost_price' => $option['cost_price'] ?? 0,
                            'goods_sn' => $option['goods_sn'] ?? '',
                            'weight' => $option['weight'] ?? 0,
                            'volume' => $option['volume'] ?? 0,
                            'display_order' => $index,
                            'created_at' => time(),
                            'updated_at' => time()
                        ]);
                    }
                }
            }

            DB::commit();

            return response()->json([
                'result' => 1,
                'msg' => '规格更新成功'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'result' => 0,
                'msg' => '规格更新失败: ' . $e->getMessage()
            ]);
        }
    }
   
}